/* s2 - find first zero byte by testing each one-for-one
   Copyright (C) 2018 Ariadne Devos

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>. */

#include <sHT/bitops.h>
#include <sHT/nospec.h>
#include <stdint.h>

_Static_assert(sizeof(uint64_t) == 8, "code assumes 8-bit bytes");

_Static_assert(sHT_word_zero_index_prepare(UINT64_C(23)) == ~UINT64_C(23), "inconsitent with <sHT/bitops.h>");

#define test_i(w, n) sHT_test_hidden((w), !((w) & (UINT64_C(0xff) << 8 * (n))))

/* noinline is for benchmarking */
__attribute__((noinline))
int
sHT_word_zero_index64(uint64_t word)
{
	if (test_i(word, 0))
		return 0;
	if (test_i(word, 1))
		return 1;
	if (test_i(word, 2))
		return 2;
	if (test_i(word, 3))
		return 3;
	if (test_i(word, 4))
		return 4;
	if (test_i(word, 5))
		return 5;
	if (test_i(word, 6))
		return 6;
	if (test_i(word, 7))
		return 7;
	return 8;
}

